package com.maxd.controller.userinfo;

import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.model.UserInfo;
import com.maxd.modules.member.service.IMemberService;
import com.maxd.respository.common.CommonRepository;
import com.maxd.respository.jifen.JiFenJpaRepository;
import com.maxd.respository.jifen.JiFenRepository;
import com.maxd.respository.order.OrderRepository;
import com.maxd.respository.userinfo.UserJpaRepository;
import com.maxd.respository.userinfo.UserRepository;
import com.maxd.service.Apple.IAppleService;
import com.maxd.service.jifen.IJiFenService;
import com.maxd.service.message.IMessageService;
import com.maxd.service.money.IMoneyDetailsService;
import com.maxd.service.userMoney.UserMoneyService;
import com.maxd.service.userinfo.IUserService;
import com.maxd.service.userinfo.UserServiceImpl;
import com.maxd.service.wx.AccountService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@RestController
@Api(value = "团长信息管理", tags = {"团长信息管理"})
@RequestMapping(value = "/user")
@Slf4j
public class TuanzhangInfoController {

    @Autowired
    private IUserService iUserService;
    @Autowired
    private UserJpaRepository userJpaRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private CommonRepository commonRepository;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private AccountService accountService;
    @Autowired
    private IMessageService iMessageService;
    @Autowired
    private IJiFenService jiFenService;
    @Autowired
    private JiFenJpaRepository jiFenRepository;
    @Autowired
    private JiFenRepository fenRepository;
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private IMoneyDetailsService iMoneyDetailsService;
    @Autowired
    private IAppleService appleService;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private IMemberService memberService;


//    @RequestMapping(value = "/getSubTuanPage", method = RequestMethod.GET)
//    @ApiOperation("获取下级团长分页")
//    @ResponseBody
//    public Result getSubTuanPage(HttpServletRequest request, @RequestParam Integer page, @RequestParam int size, @RequestParam(defaultValue = "", value = "searchKey") String searchKey) {
//
//        Object userIds = request.getAttribute("userId");
//        if (userIds == null) {
//            userIds = request.getAttribute("adminId");
//        }
//        if (userIds == null) {
//            return ResultUtil.error(-1, "未登录");
//        }
//        UserInfo userInfo = userService.getUserByUserId(String.valueOf(userIds));
//
//        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
//        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
//        Page<UserInfo> isTuan = userJpaRepository.findAll((root, query, criteriaBuilder) -> {
//            List<Predicate> conditions = new ArrayList<>();
//            if (StringUtils.isNotBlank(searchKey)) {
//                conditions.add(
//                                criteriaBuilder.or(
//                                        criteriaBuilder.like(root.get("nickName").as(String.class), "%"+searchKey+"%"),
//                                        criteriaBuilder.like(root.get("phone").as(String.class), "%"+searchKey+"%"),
//                                        criteriaBuilder.like(root.get("id").as(String.class), "%"+searchKey+"%"))
//                );
//
//            }
//
//            conditions.add(criteriaBuilder.equal(root.get("isTuan"), 1));
//            conditions.add(criteriaBuilder.equal(root.get("invitation"), userInfo.getRelationId()));
//            query.where(
//                    conditions.toArray(new Predicate[]{})
//            );
//
//
//
//            return query.getRestriction();
//
//        }, pageable);
//
//        return ResultUtil.success(isTuan);
//    }

    @RequestMapping(value = "/getSubMemberPage", method = RequestMethod.GET)
    @ApiOperation("获取下级人员分页")
    @ResponseBody
    public Result getSubMemberPage(HttpServletRequest request,
                                   @RequestParam Integer page,
                                   @RequestParam int size,
                                   @RequestParam(value = "isTuan",defaultValue = "false") boolean isTuan,
                                   @RequestParam(defaultValue = "", value = "searchKey") String searchKey) {

        Object userIds = request.getAttribute("userId");
        if (userIds == null) {
            userIds = request.getAttribute("adminId");
        }
        if (userIds == null) {
            return ResultUtil.error(-1, "未登录");
        }
        UserInfo userInfo = userService.getUserByUserId(String.valueOf(userIds));

        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        Page<UserInfo> isTuanPage = userJpaRepository.findAll((root, query, criteriaBuilder) -> {
            List<Predicate> conditions = new ArrayList<>();
            if (StringUtils.isNotBlank(searchKey)) {
                conditions.add(
                        criteriaBuilder.or(
                                criteriaBuilder.like(root.get("nickName").as(String.class), "%"+searchKey+"%"),
                                criteriaBuilder.like(root.get("phone").as(String.class), "%"+searchKey+"%"),
                                criteriaBuilder.like(root.get("id").as(String.class), "%"+searchKey+"%"))
                );

            }

            if (isTuan) {
                conditions.add(criteriaBuilder.equal(root.get("isTuan"), 1));
            }
            conditions.add(criteriaBuilder.equal(root.get("invitation"), userInfo.getRelationId()));
            query.where(
                    conditions.toArray(new Predicate[]{})
            );



            return query.getRestriction();

        }, pageable);

        return ResultUtil.success(isTuanPage);
    }

    @RequestMapping(value = "/setAsTuan", method = RequestMethod.POST)
    @ApiOperation("设置下级直属成员为团长")
    @ResponseBody
    public Result setAsTuan(HttpServletRequest request, @RequestParam String userId, @RequestParam(defaultValue = "1") Integer flag) {

        Object userIds = request.getAttribute("userId");
        if (userIds == null) {
            userIds = request.getAttribute("adminId");
        }
        if (userIds == null) {
            return ResultUtil.error(-1, "未登录");
        }
        if (flag != 0 && flag != 1) {
            return ResultUtil.error(-1, "flag参数不合法，0为取消团长1为设置团长个");
        }
        UserInfo currentUser = userService.getUserByUserId(String.valueOf(userIds));
        UserInfo user = userService.getUserByUserId(String.valueOf(userId));
        if (!Objects.equals(currentUser.getRelationId(), user.getInvitation())) {
            return ResultUtil.error(-1, "此用户不是您的下级直属");
        }

        user.setIsTuan(flag);
        userService.saveBody(user);
        return ResultUtil.success("ok");
    }

}
